Construí mi código basado en las ideas de este código:
https://github.com/davidflanagan/jstdg7/blob/master/ch12/Range.js
class SayHi { constructor (hi, repeat) { this.hi = hi; this.repeat = repeat; } [Symbol.iterator]() { let next = 1; let last = this.repeat; let hi = this.hi; return { next() { if (next<=last) { let now = next; next++; return { value: hi+now }; } else { return { done: true }; } }, // What's the use of this?? [Symbol.iterator]() { return this; } }; } } let sayHi = new SayHi("HI", 3); for(let x of sayHi) console.log(x);No entiendo cómo funciona esta línea de código desde el contexto de todo el programa, porque el programa funciona sin este código:
[Symbol.iterator]() { return this; }¿Como funciona? ¿Por qué devolvemos 2 funciones para el Symbol.iterator externo? ¿Cómo invocamos cada una de las funciones?
Este es un concepto relativamente simple, algo que yo mismo he aprendido recientemente. Si tiene un objeto iterador normal que devuelve un objeto sin el [Symbol.iterator] , esto arrojaría un error:
let data = [...iterator];Con esta línea, no solo el programa no arroja un error, sino que estos dos métodos generan exactamente lo mismo:
let data1 = [...sayHiInstance]; let data2 = [...sayHiInstance[Symbol.iterator]()];